package repository

import (
	"gorm.io/gorm"
	"shop-bean/model"
	"shop-bean/vo"
)

type IShippingTemplatesNoDeliveryRepository interface {
	FindGroup(db *gorm.DB, tempId uint) ([]*vo.ShippingTemplatesNoDeliveryVO, error)
	BatchDelete(db *gorm.DB, tempIds []uint) error
}

type ShippingTemplatesNoDeliveryRepository struct {
}

func NewShippingTemplatesNoDeliveryRepository() IShippingTemplatesNoDeliveryRepository {
	return &ShippingTemplatesNoDeliveryRepository{}
}

func (r *ShippingTemplatesNoDeliveryRepository) FindGroup(db *gorm.DB, tempId uint) (rows []*vo.ShippingTemplatesNoDeliveryVO, err error) {
	return rows, db.Raw(`
		SELECT
			g.uniq_id,
			g.province_id,
			g.city_id_str,
			sys_city. NAME name_str
		FROM
			(
				SELECT
					t.uniq_id,
					GROUP_CONCAT(DISTINCT t.city_id) AS city_id_str,
					t.province_id
				FROM
					(
						SELECT
							province_id,
							city_id,
							uniq_id
						FROM
							tz_shipping_templates_no_delivery
						WHERE
							temp_id = ?
					) t
				GROUP BY
					t.uniq_id,
					t.province_id
			) g
		LEFT JOIN tz_sys_city sys_city ON g.province_id = sys_city.city_id
    `, tempId).Find(&rows).Error
}

func (r *ShippingTemplatesNoDeliveryRepository) BatchDelete(db *gorm.DB, tempIds []uint) error {
	return db.Where("temp_id IN ?", tempIds).Delete(&model.ShippingTemplatesNoDelivery{}).Error
}

/*
SELECT
	g.uniq_id,
	g.province_id,
	g.city_id_str,
	sys_city. NAME name_str
FROM
	(
		SELECT
			t.uniq_id,
			GROUP_CONCAT(DISTINCT t.city_id) AS city_id_str,
			t.province_id
		FROM
			(
				SELECT
					province_id,
					city_id,
					uniq_id
				FROM
					tz_shipping_templates_no_delivery
				WHERE
					temp_id = 5
			) t
		GROUP BY
			t.uniq_id,
			t.province_id
	) g
LEFT JOIN tz_sys_city sys_city ON g.province_id = sys_city.city_id
*/
